import asyncio
from mitmproxy import http, options, ctx
from mitmproxy.tools.dump import DumpMaster
import json
from rapidfuzz import fuzz
import logging
from threading import Thread
# import requests
# from soruce import *
# from logging import logger

LISTENPORT = 8282

HEDAERS = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090819) XWEB/8555'
}


# 创建自定义主类以加载addons
class QuietMaster(DumpMaster):

    def run(self, *args, **kwargs):
        # 在启动前，进一步配置日志处理器，以达到静默效果
        for handler in logging.getLogger("mitmproxy").handlers:
            handler.setLevel(logging.ERROR)
        return super().run(*args, **kwargs)


# https://sajj.jlntech.cn/sajj/gthmmc/index.php?m=ias&c=manager&a=getQuestion&from=xcx&destination_id=499&type=1,2,3,4,5,6,7,8,9,10,11,&openid=oO5mg4vuBmoKNrss9hbLyrg8tuIs&checkstr=44106b4f9f8bd1d98d105dd9c0bc4a30
class ExampleAddon:

    def request(self, flow: http.HTTPFlow) -> None:
        # 在请求阶段也进行过滤，避免不必要的日志
        # if target_url not in flow.request.pretty_url:
        return

    def response(self, flow: http.HTTPFlow) -> None:
        # 在响应阶段进行过滤和处理
        return

        # if getQuestion_url in flow.request.pretty_url:
        #     global title_list
        #     global answer_list
        #     global openid
        #     global checkstr
        #     global token
        #     global SEND_FLAG
        #     params_list = flow.request.pretty_url.split('&')
        #     openid = params_list[-2].split('=')[-1]
        #     checkstr = params_list[-1].split('=')[-1]
        #     title_list = []
        #     answer_list = []
        #     print(f"\n【请求】{flow.request.pretty_url}")
        #     print(f"【响应状态码】{flow.response.status_code}")
        #     print(f"【openid】{openid}")
        #     print(f"【checkstr】{checkstr}")
        #     # print(f"【响应内容】{flow.response.text[:200]}...")
        #     '''
        #     以下为特有内容
        #     '''
        #     answers_json = flow.response.json()
        #     # print(f"【响应内容】{flow.response.json()}")
        #     answers_datalist = answers_json['datalist']
        #     token = get_token(answers_datalist)[0:27]
        #     print(f"【token】{token}")
        #     SEND_FLAG = True
        #     for data in answers_datalist:
        #         answers_title = data['title']
        #         answers_answer = data['answer']
        #         answers_choose = data[f'chose_{chr(int(answers_answer)+96)}']
        #         title_list.append(answers_title)
        #         answer_list.append(answers_choose)
        #     # print(answers_data)
        #     with open('data.json', 'w', encoding='utf-8') as f:
        #         json.dump({
        #             'title': title_list,
        #             'answer': answer_list
        #         },
        #                   f,
        #                   ensure_ascii=False,
        #                   indent=4)
        # elif getMemberToday_url in flow.request.pretty_url:
        #     global member_id
        #     global row_id
        #     global secret
        #     params_list = flow.request.pretty_url.split('&')
        #     member_id = params_list[-1].split('=')[-1]
        #     print(f"\n【请求】{flow.request.pretty_url}")
        #     print(f"【响应状态码】{flow.response.status_code}")
        #     resp_json = flow.response.json()
        #     row_id = resp_json['data']['row_id']
        #     print(f"【响应内容】{resp_json}")
        #     print(f"【member_id】{member_id}")
        #     print(f"【row_id】{row_id}")
        #     secret = get_secret(row_id, 27)
        #     print(f"【secret】{secret}")


async def start_mitmproxy_async():
    opts = options.Options(
        listen_port=LISTENPORT,  # 自定义监听端口
    )
    master = QuietMaster(opts)
    master.addons.add(ExampleAddon())
    print(f"mitmproxy正在运行，请设置代理到localhost:{LISTENPORT}...")
    await master.run()
    # print("\nmitmproxy已停止。")


def get_answers_web_data():
    try:
        asyncio.run(start_mitmproxy_async())
    except KeyboardInterrupt:
        print("\n手动中断。")


if __name__ == "__main__":
    print("按 ctrl C 停止，不要直接关闭")
    get_answers_web_data()
